#!/bin/bash

# 定义颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # 无颜色

# 检查是否有root权限
if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}请使用root权限运行此脚本${NC}"
  exit 1
fi

BASEDIR=/opt/mysql
DATADIR=/opt/mysql/data
MYSQL_VERSION=5.7.44

# 检查当前目录是否已经存在MySQL安装包
if [ ! -f "mysql-${MYSQL_VERSION}-linux-glibc2.12-x86_64.tar.gz" ]; then
  echo -e "${YELLOW}准备阶段 下载 mysql 安装包${NC}"
  wget https://downloads.mysql.com/archives/get/p/23/file/mysql-${MYSQL_VERSION}-linux-glibc2.12-x86_64.tar.gz
  if [ $? -ne 0 ]; then
    echo -e "${RED}下载 MySQL 安装包失败${NC}"
    echo "可至 https://downloads.mysql.com/archives/community/ 页面手动下载上传后，重新运行此脚本"
    exit 1
  fi
else
  echo -e "${GREEN}MySQL 安装包已存在，跳过下载步骤${NC}"
fi

# 解压MySQL安装包并移动到指定目录
echo -e "${YELLOW}step1 解压 MySQL 中...${NC}"
tar -zxf mysql-${MYSQL_VERSION}-linux-glibc2.12-x86_64.tar.gz
if [ $? -ne 0 ]; then
  echo -e "${RED}解压 MySQL 安装包失败${NC}"
  exit 1
fi
mv mysql-5.7.44-linux-glibc2.12-x86_64 "$BASEDIR"
if [ $? -ne 0 ]; then
  echo -e "${RED}移动 MySQL 安装包失败${NC}"
  exit 1
fi

# 创建mysql用户和组
echo -e "${YELLOW}step2 创建 mysql 用户及用户组${NC}"
groupadd mysql
if [ $? -ne 0 ]; then
  echo -e "${RED}创建 mysql 用户组失败${NC}"
  exit 1
fi
useradd -r -g mysql -s /bin/false mysql
if [ $? -ne 0 ]; then
  echo -e "${RED}创建 mysql 用户失败${NC}"
  exit 1
fi

# 创建必要的目录
mkdir -p "$DATADIR"
mkdir -p "$BASEDIR/conf"
mkdir -p "$BASEDIR/logs"
chown -R mysql:mysql "$DATADIR"
chown -R mysql:mysql "$BASEDIR"
chmod 750 "$DATADIR"

# 配置环境变量
cat >> /etc/profile <<EOF
export PATH=\$PATH:$BASEDIR/bin
EOF

source /etc/profile

# 安装依赖包
echo -e "${YELLOW}step3 安装依赖包...${NC}"
yum install -y libaio > /dev/null
if [ $? -ne 0 ]; then
  echo -e "${RED}安装依赖包失败${NC}"
  exit 1
fi

# 初始化MySQL数据库
echo -e "${YELLOW}step4 mysql 初始化中...${NC}"
mysqld --initialize --user=mysql --basedir=$BASEDIR --datadir=$DATADIR > /tmp/initmysql.txt 2>&1
if [ $? -ne 0 ]; then
  echo -e "${RED}初始化 MySQL 数据库失败${NC}"
  cat /tmp/initmysql.txt
  exit 1
fi

# 配置my.cnf文件
cat > "$BASEDIR/conf/my.cnf" << EOF
[mysqld]
user=mysql
basedir=/opt/mysql
datadir=/opt/mysql/data
server_id=1
port=3306
socket=/tmp/mysql.sock
log-error=/opt/mysql/logs/mysqld.log

# 常规查询日志
general_log=1
general_log_file=/opt/mysql/logs/general.log

# 慢查询日志
slow_query_log=1
slow_query_log_file=/opt/mysql/logs/slow.log
long_query_time=2

# 二进制日志
log-bin=/opt/mysql/logs/mysql-bin
binlog_format=mixed

# 缓存和内存优化
innodb_buffer_pool_size=1G  # 设置为物理内存的60%-70%，但要确保留出足够的内存给操作系统和其他应用程序。
innodb_log_file_size=256M  # 通常为缓冲池大小的25%左右。

# 设置为1确保每次事务提交后立即写入磁盘，以保证数据的持久性。对于性能和数据安全的权衡，可以设置为2（每秒写一次日志）或0（完全依赖操作系统的缓存）。
innodb_flush_log_at_trx_commit=1

# 连接和线程
max_connections=500
thread_cache_size=50

# 缓冲区和排序
key_buffer_size=256M
sort_buffer_size=4M
read_buffer_size=4M
read_rnd_buffer_size=16M
join_buffer_size=8M

# 网络和超时
wait_timeout=600
interactive_timeout=600

# 日志轮转
expire_logs_days=7
max_binlog_size=1024M

# 字符集
character-set-server=utf8mb4
collation-server=utf8mb4_general_ci

# sql_mode
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

## 客户端
[mysql]
socket=/tmp/mysql.sock
prompt=lucifer [\\d]>

# 字符集
default-character-set=utf8mb4
EOF

# 配置mysqld.service文件
cat > /usr/lib/systemd/system/mysqld.service <<EOF
[Unit]
Description=MySQL Server
Documentation=man:mysqld(8)
Documentation=https://dev.mysql.com/doc/refman/5.7/en/
After=network.target
After=syslog.target
[Install]
WantedBy=multi-user.target
[Service]
User=mysql
Group=mysql
ExecStart=$BASEDIR/bin/mysqld --defaults-file=$BASEDIR/conf/my.cnf
LimitNOFILE=5000
EOF

# 重新加载systemd服务并启动MySQL
echo -e "${YELLOW}step5 启动 mysql 并配置开机自启动${NC}"
systemctl daemon-reload
if [ $? -ne 0 ]; then
  echo -e "${RED}重新加载 systemd 服务失败${NC}"
  exit 1
fi
systemctl enable mysqld
if [ $? -ne 0 ]; then
  echo -e "${RED}配置 MySQL 开机自启动失败${NC}"
  exit 1
fi
systemctl start mysqld
if [ $? -ne 0 ]; then
  echo -e "${RED}启动 MySQL 服务失败${NC}"
  exit 1
fi
echo -e "${GREEN}=============================================================${NC}"
echo " "

# 重设root密码
# 获取临时密码
# 提示用户输入新密码
NEW_ROOT_PASSWORD=$(openssl rand -base64 12)
echo -e "${YELLOW}root密码将设置为: $NEW_ROOT_PASSWORD; 是否自定义root密码？(y/n)${NC}"
read customize
if [ "$customize" = "y" ]; then
    echo -e "${YELLOW}请输入自定义 root 用户密码: ${NC}"
    read NEW_ROOT_PASSWORD
fi

TEMP_PASSWORD=$(grep "temporary password" /tmp/initmysql.txt | awk '{print $NF}')
if [ -z "$TEMP_PASSWORD" ]; then
  echo -e "${RED}获取临时密码失败${NC}"
  exit 1
fi
echo -e "${YELLOW}临时密码: ${NC}$TEMP_PASSWORD"
mysql -uroot -p"$TEMP_PASSWORD" --connect-expired-password -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$NEW_ROOT_PASSWORD';"
if [ $? -ne 0 ]; then
  echo -e "${RED}重设 root 用户密码失败${NC}"
  exit 1
fi

# 打印新密码
echo -e "${GREEN}MySQL root用户的密码已重设为: ${NC}$NEW_ROOT_PASSWORD"
echo -e "${YELLOW}使用以下命令，修改可登录主机并刷新权限：${NC}"
echo "source /etc/profile"
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '$NEW_ROOT_PASSWORD' WITH GRANT OPTION;"
echo "FLUSH PRIVILEGES;"
echo -e "${GREEN}=============================================================${NC}"
echo "MySQL ${MYSQL_VERSION} 安装完成。管理用户: root, 密码: $NEW_ROOT_PASSWORD"